<script setup lang="ts">
  import { queryInstDeptList } from '@/api/organization/department';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import { computed, useAttrs } from 'vue';

  const attrs = useAttrs();

  const props = withDefaults(
    defineProps<{
      mode?: 'select' | 'tree';
      multiple?: boolean;
      allowClear?: boolean;
    }>(),
    {
      mode: 'select',
      multiple: false,
      allowClear: false,
    }
  );

  const modelVal = defineModel<string | number | (string | number)[]>();

  const selectedKeys = computed({
    get() {
      if (!props.multiple) {
        return [modelVal.value as string];
      }
      return modelVal.value as Array<string | number>;
    },
    set(val: (string | number)[]) {
      if (!props.multiple) {
        if (val && val.length > 0) {
          const [v] = val;
          modelVal.value = v;
        } else {
          modelVal.value = '';
        }
        return;
      }
      modelVal.value = val;
    },
  });

  const deptData = useSelectOption({
    apiFun: queryInstDeptList,
  });

  const fieldNames = {
    key: 'deptId',
    title: 'name',
    children: 'subDeptList',
  };

  Object.assign(deptData.bindProps, attrs);
</script>

<template>
  <div>
    <a-tree-select
      v-if="props.mode === 'select'"
      v-model="modelVal"
      :field-names="fieldNames"
      :multiple="props.multiple"
      :allow-clear="allowClear"
      v-bind="deptData.bindProps"
    ></a-tree-select>

    <div v-else>
      <a-tree
        v-model:selected-keys="selectedKeys"
        :multiple="props.multiple"
        :field-names="fieldNames"
        v-bind="deptData.bindProps"
      />
    </div>
  </div>
</template>

<style lang="less" scoped></style>
